﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using youtubeFisher;

namespace Gpf.Whs.YouTubeDownloader.CommSrv
{
    public static class DownloadEngine
    {
        private static Dictionary<string, DownloadItem> _downloads = new Dictionary<string, DownloadItem>();
        private static object _lock = new object();

        public static void StartDownload(string url, string path, byte format)
        {
            var service = YouTubeService.Create(url);
            var formatInfo = service.AvailableVideoFormat.First(f => f.FormatCode == format);

            var downloadItem = new DownloadItem();          
            downloadItem.Key = DateTime.Now.Ticks.ToString();
            downloadItem.Title = service.VideoTitle;
            downloadItem.Length = formatInfo.VideoSize;
            downloadItem.Url = formatInfo.VideoUrl;
            downloadItem.DownloadDone += DownloadDone;
            downloadItem.TargetPath = path;

            _downloads.Add(downloadItem.Key, downloadItem);

            ThreadPool.QueueUserWorkItem(new WaitCallback(downloadItem.Download));
        }

        public static DownloadItemStatus[] GetDownloadStatuses()
        {
            lock (_lock)
            {
                return (from d in _downloads
                        select new DownloadItemStatus
                        {
                            Title = d.Value.Title,
                            Key = d.Key,
                            Downloaded = d.Value.CurrentlyDownloaded,
                            DownloadSize = d.Value.Length,
                            PercentDownloaded = d.Value.PercentDownloaded
                        }).ToArray();
            }
        }

        public static void CancelDownload(string key)
        {
            var path = string.Empty;

            lock (_lock)
            {
                var item = _downloads[key];
                path = item.FullPath;
                item.StopDownload();
                item.Dispose();

                _downloads.Remove(key);
            }

            Thread.Sleep(2000);
            File.Delete(path);
        }

        private static void DownloadDone(string key)
        {
            Debug.WriteLine("Download done!");

            lock (_downloads)
            {
                _downloads.Remove(key);
            }
        }
    }
}
